package com.fulu.javabase.juc.tools;

import java.util.concurrent.*;

public class ToolsTest {

    private static final ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 10, 0, TimeUnit.MILLISECONDS,
            new LinkedBlockingDeque<Runnable>(100));

    public static void main(String[] args) throws InterruptedException {
        Semaphore s = new Semaphore(3,true);
        Thread[] threads = new Thread[30];
        for (int i = 0; i <threads.length ; i++) {
            threads[i] = new Thread(()->{
                try {
                    s.acquire();
                    System.out.println(Thread.currentThread().getName()+": 我acquire到了");
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    s.release();
                }
            });
        }

        for(Thread thread:threads){
            thread.start();
        }


    }

    private static void cyclicBarrierTest() {
        final CyclicBarrier cyclicBarrier = new CyclicBarrier(10, () ->{
            System.out.println("线程数达到10");
        });

        for (int i = 0; i < 100; i++) {
            executor.submit(() -> {
                try {
                    cyclicBarrier.await();
                    System.out.println(Thread.currentThread().getName());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            });
        }

        executor.shutdown();
    }

    private static void countDownLatchTest() throws InterruptedException {

        final CountDownLatch countDownLatch = new CountDownLatch(10);

        for (int i = 0; i < 10; i++) {
            executor.submit(() -> {
                try {
                    Thread.sleep(500);
                    System.out.println(Thread.currentThread().getName() + "执行完毕");
                    countDownLatch.countDown();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }

        countDownLatch.await();
        System.out.println("线程执行完毕");
        executor.shutdownNow();
    }
}
